import archiver from "archiver";
import fs from "fs";
import path from "path";

// 定义插件选项接口
interface ZipPluginOptions {
  filename?: string;
  outputPath?: string;
  compressionLevel?: number;
  addDateComment?: boolean;
}

class ZipPlugin {
  private options: Required<ZipPluginOptions>;

  constructor(options: ZipPluginOptions = {}) {
    this.options = Object.assign({
      filename: 'dist.zip',
      outputPath: 'dist-zip',
      compressionLevel: 9,
      addDateComment: true
    }, options);
  }

  apply(compiler: any) {
    // 只在生产环境下运行
    if (process.env.NODE_ENV !== "production") {
      return;
    }

    compiler.hooks.afterEmit.tapAsync('ZipPlugin', (compilation:any, callback:any) => {
      const outputDir = path.resolve(process.cwd(), "dist");
      const zipDir = path.resolve(process.cwd(), this.options.outputPath);
      const zipFile = path.join(zipDir, this.options.filename);
      
      // 添加日期注释到 HTML 文件
      if (this.options.addDateComment) {
        const htmlFilePath = path.join(outputDir, "index.html");
        if (fs.existsSync(htmlFilePath)) {
          const currentDate = new Date().toLocaleString("zh-CN", { timeZone: "Asia/Shanghai" });
          fs.appendFileSync(htmlFilePath, `\n<!-- Build Date: ${currentDate} -->`);
          console.log(`已在 HTML 文件末尾添加日期注释: ${currentDate}`);
        }
      }

      // 确保 zip 输出目录存在
      if (!fs.existsSync(zipDir)) {
        fs.mkdirSync(zipDir, { recursive: true });
      }

      // 创建 zip 文件
      const output = fs.createWriteStream(zipFile);
      const archive = archiver("zip", { zlib: { level: this.options.compressionLevel } });

      output.on("close", () => {
        console.log(`打包完成: ${zipFile} (${archive.pointer()} total bytes)`);
        callback();
      });

      archive.on("error", (err) => {
        throw err;
      });

      archive.pipe(output);
      archive.directory(outputDir, "dist"); // 添加 "dist" 作为目录层级
      archive.finalize(); // 确保在修改 HTML 文件后调用
    });
  }
}

// 导出默认实例
export default ZipPlugin;
// 为了兼容 CommonJS 的 require() 调用
if (typeof module !== 'undefined' && typeof module.exports !== 'undefined') {
  Object.defineProperty(module.exports, "__esModule", { value: true });
  module.exports = Object.assign(module.exports.default, module.exports);
}